package com.coffee.wx.uitls;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.XmlUtil;
import jakarta.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class TypeChangeUtils {

    /**
     * 将bean对象转换为xml字符串
     * 获取bean的属性名，首字母转化为大写后作为map的key，bean的属性值作为map的value
     *
     * @param bean
     * @return
     */
    public static String beanToXmlStr(Object bean) {

        Map<String, Object> resulMap = new HashMap<>();

        if(Map.class.isAssignableFrom(bean.getClass())){
            return XmlUtil.mapToXmlStr((Map)bean, true);
        }

        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            String upperKey = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            Object value = BeanUtil.getFieldValue(bean, fieldName);
            resulMap.put(upperKey, value);
        }

        String xml = XmlUtil.mapToXmlStr(resulMap, true);
        Console.log(" xml ====> " + xml);
        return xml;
    }

    /**
     * 将map型转为请求参数型
     *
     * @param data
     * @return
     */
    public static String urlencode(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 将request中的参数转换为字符串
     *
     * @param request
     * @return
     */
    public static String requestToMap(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 实际应用中你可能需要返回一个错误响应或进行其他错误处理
        }
        return sb.toString();
    }

}
